/**
 * 
 */
package com.ls.x.activity;

import java.util.ArrayList;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.ls.x.R;
import com.ls.x.tool.DatabaseHelper;

/**
 * @author 李靖
 */
public class IndexActivity extends ListActivity {
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		Log.d("lijing", "IndexActivity进入onPause()");
		super.onPause();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		super.onStart();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();

		getContextListItems("select * from context where user_id ='lijing'",
				"title");
		if (isMultiSelectMode) {
			isMultiSelectMode = false;
			alterMultiSelectMode();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d("lijing", "IndexActivity进入onDestroy()");
		super.onStop();
		if (db != null) {
			db.close();
		}
		if (dbHelper != null) {
			dbHelper.close();
		}
		super.finish();
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		manager.killBackgroundProcesses(getPackageName());
	}

	private ArrayAdapter<String> adapter = null;
	private DatabaseHelper dbHelper = null;
	private SQLiteDatabase db = null;
	private Cursor cursor = null;
	private ArrayList<Long> context_list = null;
	private ListView context_listview = null;
	private long select_id = 0;
	private String[] titles_lists;
	private boolean isMultiSelectMode = false;
	private Builder b = null;
	private boolean isItemChecked = false;

	static final int PROGRESS_DIALOG = 0;
	private ProgressThread progressThread;
	private ProgressDialog progressDialog;
	private int total = 0;
	private int allDeleteItemCount = 0;
	private int deletedItemCount = 0;
	ArrayList<Long> deletelist = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 初始化一些成员变量
		dbHelper = DatabaseHelper.getDBhelper(IndexActivity.this);
		db = dbHelper.getReadableDatabase();

		setContentView(R.layout.page_index);
		context_listview = (ListView) findViewById(android.R.id.list);
		// context_listview.setLongClickable(true);
		// context_listview
		// .setOnItemLongClickListener(new ListItemLongPressListener());
		context_listview
				.setOnCreateContextMenuListener(new ListItemLongPressListener());

		// 打开程序，进入首页，对列表进行初始化
		getContextListItems("select * from context where user_id ='lijing'",
				"title");

		// 按钮“自己的”事件绑定
		Button btn_selfcontent = (Button) findViewById(R.id.btn_self);
		btn_selfcontent.setOnClickListener(new SelfContentBtnListener());
		// 按钮“好友的”事件绑定
		Button btn_friendcontent = (Button) findViewById(R.id.btn_friendcontent);
		btn_friendcontent.setOnClickListener(new FriendContentBtnListener());

		// 按钮“增加”事件绑定
		Button btn_add = (Button) findViewById(R.id.btn_add);
		btn_add.setOnClickListener(new AddContextListener());
	}

	// 全屏
	public void setFullscreen() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	// 无标题
	public void setNoTitle() {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		if (isMultiSelectMode) {
			// sparsebooleanarray

		} else {
			Intent intent = new Intent();
			intent.setClass(this, ContentShowActivity.class);
			select_id = context_list.get(position);
			intent.putExtra("context_id", select_id);
			startActivity(intent);
			l.setSelection(position);
		}

	}

	// 长按条目上下文菜单监听
	public boolean onContextItemSelected(MenuItem item) {
		/*
		 * 选项：0删除该项 1编辑该项 2多选模式 3全选 4取消全选
		 */
		IndexActivity.this.closeContextMenu();
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		select_id = context_list.get(menuInfo.position);
		int which = item.getItemId();
		if (isMultiSelectMode) {
			// 如果进入了多选模式
			switch (which) {
			case 0:
				checkDeleteSelected();
				break;
			case 1:
				alterMultiSelectMode();
				break;
			case 2:
				selectAll();
				break;
			case 3:
				cancleSelectAll();
				break;
			}
		} else {
			// 如果是正常模式
			switch (which) {
			case 0:
				checkDelete();
				break;
			case 1:
				editContext();
				break;
			case 2:
				alterMultiSelectMode();
				break;
			}
		}
		return super.onContextItemSelected(item);
	}

	// 长安菜单监听-确认是否删除条目的对话框
	public void checkDelete() {
		b = new AlertDialog.Builder(IndexActivity.this);
		b.setTitle(R.string.text_check_delete_context_dialog_title);
		b.setMessage(R.string.text_check_delete_context_dialog_message);
		// 点击了确定按钮
		b.setPositiveButton(R.string.text_dialog_ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.d("lijing", "确认删除条目" + select_id);
						removeContextListItem(select_id);
						getContextListItems(
								"select * from context where user_id ='lijing'",
								"title");
					}
				});
		// 点击了取消按钮
		b.setNegativeButton(R.string.text_dialog_cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.d("lijing", "取消删除条目");
					}
				});
		b.create().show();
	}

	// 长安菜单监听-多选模式
	public void alterMultiSelectMode() {
		Log.d("lijing", "进入alterMultiSelectMode():isMultiSelectMode="
				+ isMultiSelectMode);
		if (isMultiSelectMode) {
			isMultiSelectMode = false;
			adapter = new ArrayAdapter<String>(IndexActivity.this,
					android.R.layout.simple_list_item_1, titles_lists);
			// 设置该窗口显示列表
			context_listview.setAdapter(adapter);
		} else {
			isMultiSelectMode = true;
			adapter = new ArrayAdapter<String>(IndexActivity.this,
					android.R.layout.simple_list_item_multiple_choice,
					titles_lists);
			// 设置该窗口显示列表
			context_listview.setAdapter(adapter);
			context_listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		}
	}

	// 长安菜单监听-确认是否删除多选条目的对话框
	public void checkDeleteSelected() {
		b = new AlertDialog.Builder(IndexActivity.this);
		b.setTitle(R.string.text_check_delete_context_dialog_title);
		b.setMessage(R.string.text_check_delete_context_dialog_message);
		// 点击了确定按钮
		b.setPositiveButton(R.string.text_dialog_ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 获得多选模式下的被选项
						deletelist = new ArrayList<Long>();

						for (int i = 0; i < titles_lists.length; i++) {
							isItemChecked = context_listview
									.getCheckedItemPositions().get(i);
							if (isItemChecked) {
								select_id = context_list.get(i);
								deletelist.add(select_id);
							}
						}
						// showDialog(PROGRESS_DIALOG);
						progressDialog = new ProgressDialog(IndexActivity.this);
						progressDialog
								.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						progressDialog.setMessage("Loading...");
						progressDialog.show();
						progressThread = new ProgressThread(handler);
						progressThread.start();

						allDeleteItemCount = deletelist.size();
						DeleteItemThread deleteItemThread = new DeleteItemThread();
						deleteItemThread.start();
					}
				});
		// 点击了取消按钮
		b.setNegativeButton(R.string.text_dialog_cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.d("lijing", "取消删除条目");
					}
				});
		b.create().show();
	}

	public void selectAll() {
		for (int i = 0; i < titles_lists.length; i++) {
			context_listview.setItemChecked(i, true);
		}
	}

	public void cancleSelectAll() {
		for (int i = 0; i < titles_lists.length; i++) {
			context_listview.setItemChecked(i, false);
		}
	}

	// 编辑条目操作
	public void editContext() {
		Log.d("lijing", "编辑条目" + select_id);
		Intent intent = new Intent();
		intent.putExtra("context_id", select_id);
		intent.setClass(IndexActivity.this, ContentEditActivity.class);
		startActivity(intent);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(Menu.NONE, 2, 0, "设置");
		menu.add(Menu.NONE, 3, 0, "关于");
		menu.add(Menu.NONE, 4, 0, "帮助");

		return super.onCreateOptionsMenu(menu);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Log.d("lijing", "点击的设置菜单" + item.getItemId());
			break;
		case 2:
			Log.d("lijing", "点击的关于菜单" + item.getItemId());
			break;
		case 3:
			Log.d("lijing", "点击的帮助菜单" + item.getItemId());
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 获得数据库中的条目，并且更新至ListView中
	public void getContextListItems(String SQL, String columnName) {
		context_list = new ArrayList<Long>();
		cursor = db.rawQuery(SQL, null);
		titles_lists = new String[cursor.getCount()];
		int n = 0;
		long id;
		while (cursor.moveToNext()) {
			id = Long.parseLong(cursor.getString(cursor.getColumnIndex("id")));
			titles_lists[n] = cursor.getString(2);
			context_list.add(id);
			n++;
		}

		adapter = new ArrayAdapter<String>(IndexActivity.this,
				android.R.layout.simple_list_item_1, titles_lists);

		// 设置该窗口显示列表
		context_listview.setAdapter(adapter);
		// context_listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}

	public void removeContextListItem(long context_id) {
		db.execSQL("delete from context where id = " + context_id);
	}

	// 为“自己的”按钮添加事件监听器
	class SelfContentBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// 需要根据具体的用户完成查询SQL
			getContextListItems(
					"select * from context where user_id ='lijing'", "title");
		}
	}

	// 为“好友的”按钮添加事件监听器
	class FriendContentBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			getContextListItems(
					"select * from context where user_id !='lijing'", "title");
		}
	}

	class SearchBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {

			Toast.makeText(IndexActivity.this, "点击了查询按钮", Toast.LENGTH_SHORT)
					.show();
		}
	}

	class VoiceBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {

			Toast.makeText(IndexActivity.this, "点击了录音按钮", Toast.LENGTH_SHORT)
					.show();
		}

	}

	class PhotoBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {

			Toast.makeText(IndexActivity.this, "点击了照相按钮", Toast.LENGTH_SHORT)
					.show();
		}
	}

	class CalendarBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			Toast.makeText(IndexActivity.this, "点击了日历按钮", Toast.LENGTH_SHORT)
					.show();
		}
	}

	class FriendBtnListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			Toast.makeText(IndexActivity.this, "点击了好友按钮", Toast.LENGTH_SHORT)
					.show();
		}
	}

	class AddContextListener implements OnClickListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.view.View.OnClickListener#onClick(android.view.View)
		 */
		String[] dialogitems;

		@Override
		public void onClick(View v) {
			b = new AlertDialog.Builder(IndexActivity.this);
			b.setTitle(R.string.text_add_content_button_dialog_title);
			dialogitems = getResources().getStringArray(
					R.array.dialog_items_add_content);
			b.setItems(dialogitems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case 0:
						Intent intent = new Intent();
						// Intent intent = getIntent();//不能如此获得Intent实例
						intent.setClass(IndexActivity.this,
								ContentEditActivity.class);
						startActivity(intent);
						break;
					case 1:
						Log.d("lijing", dialogitems[which]);
						break;
					case 2:
						Log.d("lijing", dialogitems[which]);
						break;
					}
				}
			});
			b.create().show();
		}
	}

	class ListItemLongPressListener implements View.OnCreateContextMenuListener {

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			menu.clear();
			menu.setHeaderTitle(R.string.menu_index_page_title);
			// 添加菜单条目
			Log.d("lijing", "进入ListItemLongPressListener:isMultiSelectMode="
					+ isMultiSelectMode);
			if (!isMultiSelectMode) {
				menu.add(0, 0, 1, R.string.menu_index_page_delete_this_item);
				menu.add(0, 1, 2, R.string.menu_index_page_edit_this_item);
				menu.add(0, 2, 3, R.string.menu_index_page_muti_select_model);
			} else {
				menu.add(0, 0, 1, R.string.menu_index_page_delete_selected_item);
				menu.add(0, 1, 2, R.string.menu_index_page_normal_select_model);
				menu.add(0, 2, 3, R.string.menu_index_page_select_all);
				menu.add(0, 3, 4, R.string.menu_index_page_cancle_select_all);
			}

		}
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			total = msg.getData().getInt("total");
			progressDialog.setProgress(allDeleteItemCount);
			if (total >= allDeleteItemCount) {
				// dismissDialog(PROGRESS_DIALOG);
				progressDialog.dismiss();
				progressThread.setState(ProgressThread.STATE_DONE);
			}
		}
	};

	/** Nested class that performs progress calculations (counting) */
	private class ProgressThread extends Thread {
		Handler mHandler;
		final static int STATE_DONE = 0;
		final static int STATE_RUNNING = 1;
		int mState;
		int total_t;
		Bundle b;
		Message msg;

		ProgressThread(Handler h) {
			mHandler = h;
		}

		public void run() {
			mState = STATE_RUNNING;
			total_t = 0;
			while (mState == STATE_RUNNING) {
				total_t = deletedItemCount;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					Log.e("ERROR", "Thread Interrupted");
				}
				msg = mHandler.obtainMessage();
				b = new Bundle();
				b.putInt("total", total_t);
				msg.setData(b);

				mHandler.sendMessage(msg);
			}

		}

		/*
		 * sets the current state for the thread, used to stop the thread
		 */
		public void setState(int state) {
			mState = state;
		}
	}

	private class DeleteItemThread extends Thread {

		public void run() {
			for (int i = 0; i < deletelist.size(); i++) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					Log.e("ERROR", "Thread Interrupted");
				}
				deletedItemCount++;
				removeContextListItem((Long) deletelist.get(i));
			}
			Message msg = new Message();
			msg.what = 1;
			handler_fresh.sendMessage(msg);
		}
	}

	private Handler handler_fresh = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				// UI线程中调用此方法通知观察者(源码中关于adapter存在一个observer,未深究！)adapter数据已改变，刷新view
				// adapter.notifyDataSetChanged();
				getContextListItems(
						"select * from context where user_id ='lijing'",
						"title");
				break;
			}
		}
	};
}
